// const {
//   info
// } = require("../../../utils/logs");
var location = require("../../../mybehaviors/location/location");
import tool from "../../../utils/util";
// packageA/member/coupon_v2_detail/coupon_v2_detail.js
var app = getApp();
Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    info: '',
    rechargeNum: 1,
    config_info: {
      switch: 0
    },
    presentershow: false,
    showRechargePay: false,
    multiple_use: {
      is_open: false,
      nums: 0
    }, //是否开启多张赠送
    content: "",
    share_coupon: '',
    showSelect: false,
    couponId: '',
    // 95337优化 优惠券
    storeCoupon: null, //门店，平台商品和门店
    active: 0,
    // 门店数据
    store_page: 1,
    store_isLoadMore: true,
    store_total_page: 0,
    store_list: [],
    // 门店商品数据
    isLoadMore: true,
    goods_page: 1,
    total_page: 0,
    goods_list: [],
    point: {
      lng: '',
      lat: ''
    },
    // this.info.num换成couponNum  拥有的券数量
    couponNum: '',
    // 该优惠券是否  折叠
    combine: false,
    // 是否是门店独立后台发布 true 或者 总后台发布 false
    is_shop: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
    console.log(options);
    if (options.id) {
      this.setData({
        couponId: options.id
      })
    }
    if (options.combine && options.combine_show != "undefined") {
      this.setData({
        combine: options.combine
      });
    }
    if (options.combine_show == "false" || options.combine_show == "undefined") {
      this.data.couponNum = 1;
    }
    // if (options.share) {
    //   this.setData({
    //     share_coupon: options.share
    //   })
    
    this.init();
    this.getdetail();
  },
  toStore(e){
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageC/o2o/o2oStore/o2oStore?store_id='+id,
    })
  },
  toGoodsStore(e){
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id='+id,
    })
  },
  tapShare() {
    this.setData({
      showSelect: true
    })
  },
  init() {
    this.setData({
      showSelect: false,
      showPresenter: false,
      verification: false,
      shareNum: 1,
    })
  },
  shareConfirm() {
    if (this.data.shareNum > this.data.multiple_use.nums) {
      wx.showToast({
        title: `分享张数不足，最多${this.data.multiple_use.nums}张`,
        icon: 'none',
        duration: 1000
      })
      return;
    } else {
      this.setData({
        couponNum: this.data.shareNum
      })
      let json = {
        couponNum: this.data.couponNum,
        // info: this.data.datainfo,
        // combine: this.data.combine,
      }
      if(this.data.combine && this.data.combine != 'undefined'){
        json.combine = this.data.combine;
      }
      wx.navigateTo({
        url: '/packageI/CouponShareShow/CouponShareShow?info=' + JSON.stringify(json) + '&id=' + this.data.couponId,
      })
    }
  },
  closeShare() {
    this.setData({
      showSelect: false
    })
  },
  shareMunTap(e) {
    console.log(e)
    this.setData({
      shareNum: e.detail
    })
  },
  //赠送优惠券
  presenter(item, index) {
    let that = this;
    console.log(item, this.info);
    // let item = e.currentTarget.dataset.item;
    // let index = e.currentTarget.dataset.index;
    that.setData({
      'usermessage.value': '',
      'usermessage.item': '',
      'usermessage.index': '',
      memberInfo: ''
    });
    that.setData({
      'usermessage.item': item,
      'usermessage.index': index,
      'presentershow': true
    });
  },
  onclose(event) {
    let that = this;
    that.setData({
      'usermessage.value': '',
      'usermessage.item': '',
      'usermessage.index': ''
    });
    that.setData({
      presentershow: false
    });
  },
  usermesbut: function (e) {
    let val = e.detail.value;
    this.setData({
      'usermessage.value': val
    });
  },
  usermesbutInput(e) {
    let val = e.detail.value;
    this.data.usermessage.value = val;
  },
  onconfirm(event) {
    let that = this;
    console.log(this.data.usermessage);
    if (app._isTextEmpty(this.data.usermessage.value)) {
      wx.showToast({
        icon: 'none',
        title: '用户ID不能为空',
        duration: 1000
      });
      this.setData({
        presentershow: false
      });
      return;
    }
    if (this.data.memberInfo == '查无此用户') {
      wx.showToast({
        icon: 'none',
        title: '查询不到该用户ID，请确认无误!',
        duration: 1000
      });
      return;
    }
    if (this.data.config_info.switch) {
      this.setData({
        showRechargePay: true
      });
      return;
    }
    that._presenterPost();
  },
  // getNavTop(){
  //   var query = wx.createSelectorQuery();
  //   query.select('#navbar').boundingClientRect(function (res) {
  //     if(res && res.top > 0){
  //       console.log(res,'dddddss')
  //     }
  //   }).exec();
  // },
  onPageScroll(e){
    // this.getNavTop();
  },
  //赠送post
  _presenterPost() {
    let that = this;
    let urlStr = app.getNetAddresss("coupon.coupon-transfer.index");
    urlStr += "&recipient=" + this.data.usermessage.value;
    urlStr += "&record_id=" + this.data.couponId;
    if (this.data.config_info.switch) {
      urlStr += "&quantity=" + this.data.rechargeNum;
      urlStr += "&coupon_id=" + this.data.couponId;
    } else {
      urlStr += "&transfer_num=" + this.data.rechargeNum;
    }
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (that.data.config_info.switch) {
            //跳转支付手续费
            wx.navigateTo({
              url: '/packageD/buy/orderPay/orderPay?order_id=' + res.data.order_ids + '&status=2'
            });
            return;
          }
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000,
            success: function (e) {
              if (that.data.combine) {
                that.setData({
                  couponNum: that.data.couponNum - 1
                });
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  });
                }, 1000);
              } else {
                setTimeout(() => {
                  wx.navigateBack({
                    delta: 1,
                  });
                }, 1000);
              }

            }
          });
          that.setData({
            presentershow: false
          });

        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          that.setData({
            presentershow: false
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getmemberInfo(e) {
    let val = e.detail.value;
    var that = this;
    let urlStr = app.getNetAddresss("member.member.memberInfo");
    urlStr += '&uid=' + val;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            memberInfo: res.data ? res.data.nickname : '查无此用户'
          });
        } else {
          that.setData({
            memberInfo: '查无此用户'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getdetail() {
    let urlStr = app.getNetAddresss("coupon.member-coupon.get-detail");
    urlStr += "&record_id=" + this.data.couponId;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            datainfo: res.data.coupon,
            rule: res.data.rule,
            img_url: res.data.img_url,
            isPresenter: res.data.transfer
          })
          let config_info = res.data.coupon_fee_plugin;
          if(config_info){
            config_info.switch = parseInt(config_info.switch);
          }
          if (res.data.coupon_fee_plugin) {
            this.setData({
              config_info: config_info
            })
          }
          if (res.data.multiple_use) {
            this.setData({
              couponNum: res.data.multiple_use.nums,
              multiple_use: res.data.multiple_use
            })
          }
          if (res.data.coupon) {
            this.setData({
              content: res.data.coupon.content
            })
            if (res.data.coupon.use_type == 9 || res.data.coupon.use_type == 4 || res.data.coupon.use_type == 5) {
              this._getLocation((res) => {
                this.data.point.lat = res.ad_info.location.lat;
                this.data.point.lng = res.ad_info.location.lng;
              });
              this.getCouponSetting();
            }
          }
          if (res.data.share_coupon) {
            this.setData({
              share_coupon: res.data.share_coupon
            })
          }
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getCouponSetting() {
    let json = {
      coupon_id: this.data.datainfo.id,
      store_page: this.data.store_page,
      goods_page: this.data.goods_page,
      longitude: this.data.point.lng ? this.data.point.lng : '',
      latitude: this.data.point.lat ? this.data.point.lat : '',
    }
    let urlStr = app.getNetAddresss("coupon.member-coupon.get-store-and-goods");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res)
          this.setData({
            storeCoupon: res.data,
            store_list: res.data.is_all_store == 0 ? res.data.store_list.data : res.data.store_list,
            goods_list: res.data.is_all_good == 0 ? res.data.goods_list.data : res.data.goods_list,
            is_shop: res.data.is_shop,
          })
          console.log(this.data.store_list,'ddddddddddddd')
          if (!res.data.is_shop) {
            if (res.data.condition_type == 1) {
              console.log(res.data.goods_list)
              // condition_type等于1时没有商品数据
              this.setData({
                isLoadMore: true,
                store_page: 1,
                total_page: res.data.store_list.last_page,
                store_list:res.data.store_list.data
              })
            } else {
              // 门店加载
              this.setData({
                isLoadMore: true,
                goods_page: 1,
                total_page: res.data.goods_list.last_page,
                store_isLoadMore: true,
                store_page: 1,
                store_total_page: res.data.store_list.last_page
              })
            }
          }
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  initList(e){
    this.setData({
      'storeCoupon.store_list.data':[],
      goods_list:[],
      isLoadMore:true,
      goods_page:1,
      total_page:0,
      'storeCoupon.goods_list.data':[],
      store_list:[],
      store_isLoadMore:true,
      store_page:1,
      store_total_page:0,
      active:e.detail.index
    })
    // console.log(e,'dddddddd')
    // this.data.active = e.detail.index;
    this.getCouponSetting();
  },
  rentDeleteNumber() {
    let that = this;
    if (this.data.rechargeNum - 1 <= 0) {
      wx.showToast({
        icon: 'none',
        title: `转赠张数至少一张`,
        duration: 1000
      });
      that.setData({
        rechargeNum: 1
      });
      return;
    } else {
      that.setData({
        rechargeNum: that.data.rechargeNum - 1
      });
    }
  },
  rentAddNumber() {
    let that = this;
    if (this.data.rechargeNum + 1 > this.data.multiple_use.nums) {
      app.tips(`分享张数不足,当前可转赠数量为${that.data.multiple_use.nums}张`);
      return;
    } else {
      that.setData({
        rechargeNum: that.data.rechargeNum + 1
      });
    }
  },
  changeRechargeNum(e) {
    let val = Number(e.detail.value);
    let that = this;
    if (val > this.data.multiple_use.nums) {
      app.tips(`分享张数不足,当前可转赠数量为${that.data.multiple_use.nums}张`);
      that.setData({
        rechargeNum: that.data.multiple_use.nums
      });
    }
  },
  //立即使用    通过类型去查询可用商品
  goBuy(e) {
    // console.log(item)
    let item = this.data.datainfo;
    console.log(item);
    if (item.use_type == 0) { //0商城通用
      this.goHome();
    } else if (item.use_type == 1) { //1指定分类
      if (item.plugin_id == 32) {
        wx.navigateTo({
          url: '/packageC/o2o/StoreSearch/StoreSearch?store_id=' + item.storeids + "&cid=" + item.category_ids
        });
        return;
      }
      wx.navigateTo({
        url: '/packageB/member/category/catelist/catelist?id=' + JSON.stringify(item.category_ids) +
          '&fromHome=1'
      });
    } else if (item.use_type == 2 || item.use_type == 8) { //2指定商品
      if (item.plugin_id == 32) {
        wx.navigateTo({
          url: '/packageC/o2o/StoreSearch/StoreSearch?store_id=' + item.storeids + "&goods_ids=" + item.goods_ids.join(",")
        });
      } else {
        wx.navigateTo({
          url: '/packageB/member/category/search_v2/search_v2?coupon=' + item.id + '&fromHome=1'
        });
      }

    } else if (
      item.use_type === 4 &&
      Array.isArray(item.storeids)
    ) {
      //4门店列表
      wx.navigateTo({
        url: '/packageC/o2o/o2oHome/o2oHome'
      });
    } else if (
      item.use_type === 5 &&
      typeof item.storeids === "number"
    ) {
      //5单门店
      wx.navigateTo({
        url: '/packageC/o2o/o2oStore/o2oStore?store_id=' + item.storeids
      });
    } else if (
      item.use_type === 7 &&
      Array.isArray(item.hotel_ids)
    ) {
      wx.navigateTo({
        url: '/packageC/hotel/HotelIndex/HotelIndex'
      });
    } else if (
      item.use_type === 6 &&
      typeof item.hotel_ids === "number"
    ) {
      wx.navigateTo({
        url: '/packageC/hotel/HotelHome/HotelHome?id=' + item.hotel_ids
      });
    } else {
      this.goHome();
    }
  },
  goHome() {
    wx.reLaunch({
      url: '/packageG/index/index',
    });
  },
  scrollChange(e){
    console.log(e)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      showSelect:false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getMoreData();
  },
  getMoreData(){
    console.log(this.data.storeCoupon,'dddddd')
    if(!this.data.storeCoupon) return
    if (this.data.storeCoupon.condition_type == 2) { 
      if (this.data.storeCoupon.is_all_good == 1 || this.data.storeCoupon.is_all_good == 1) {
        // 等于1只显示10个数据，点击加载更多跳转到md商品页
        return
      }
    }
    let json = {
      coupon_id: this.data.datainfo.id,
      longitude: this.data.point.lng ? this.data.point.lng : '',
      latitude: this.data.point.lat ? this.data.point.lat : '',
      store_page: this.data.store_page,
      goods_page: this.data.goods_page
    }
    this.data.isLoadMore = false; // 防止多次请求分页数据
    this.data.store_isLoadMore = false;
    console.log(this.data.active)
    if (this.data.active == 1) {
      console.log(this.data.store_page,this.data.total_page)
      if (this.data.store_page >= this.data.store_total_page) {
        return;
      }
      this.data.store_page = this.data.store_page + 1;
      json.store_page = this.data.store_page;
    } else {
      console.log(this.data.goods_page,this.data.total_page)
      if (this.data.goods_page >= this.data.total_page) {
        return;
      }
      this.data.goods_page = this.data.goods_page + 1;
      json.goods_page = this.data.goods_page;
    }
    let urlStr = app.getNetAddresss("coupon.member-coupon.get-store-and-goods");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        console.log(res,'ddddd')
        if (res.result == 1) {
          let nextData = [];
          if(this.data.active == 0){
            nextData = res.data.goods_list.data;
            this.setData({
              isLoadMore:true,
              goods_list:this.data.goods_list.concat(nextData)
            })
          }else{
            nextData = res.data.store_list.data;
            this.setData({
              store_isLoadMore:true,
              store_list:this.data.store_list.concat(nextData)
            })
          }
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  tapMoreBtn() {
    if (this.data.active == 0) {
      wx.navigateTo({
        path:'/packageG/index/index'
      })
    } else if (this.data.active == 1) {
      wx.navigateTo({
        url: '/packageC/o2o/o2oHome/o2oHome'
      });
     
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let name = wx.getStorageSync('nickname');
    return {
      path: "/packageA/member/coupon_v2/coupon_v2",
      title: `${name}向您分享了优惠券`
    };
  },
  onShareTimeline() {
    let name = wx.getStorageSync('nickname');
    return {
      title: `${name}向您分享了优惠券`
    };
  },
});